package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    //不喜欢行为记录
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
        //判断操作类型
        if (dto.getType() == (short) 0) {
            //不喜欢,查询不喜欢是否存在
            Query query = Query.query(Criteria.where("entryId").is(dto.getEquipmentId().toString()).and("articleId").is(dto.getArticleId()));
            ApUnlikesBehavior apUnlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
            //非空判断
            if (apUnlikesBehavior != null) {
                //已经存在不喜欢行为
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "对该文章已经不喜欢,请勿重复操作!");
            } else {
                //没有不喜欢行为,新增
                apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setCreatedTime(new Date());
                apUnlikesBehavior.setEntryId(dto.getEquipmentId().toString());
                apUnlikesBehavior.setType((short)0);
                //插入数据库
                mongoTemplate.save(apUnlikesBehavior);
                //响应调用者
                return ResponseResult.okResult();
            }
        } else {
            //取消不喜欢
            Query query = Query.query(Criteria.where("entryId").is(dto.getEquipmentId().toString()).and("articleId").is(dto.getArticleId()));
            ApUnlikesBehavior apUnlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
            //非空判断
            if (apUnlikesBehavior == null) {
                //没有不喜欢
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "您还没有不喜欢该文章,不需要取消!");
            } else {
                //有不喜欢,删除
                mongoTemplate.remove(apUnlikesBehavior);
                //响应调用者
                return ResponseResult.okResult();
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW);
    }
}
